"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Loader2 } from "lucide-react";
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
import { z } from "zod";

import { useCreateOutputMutation } from "@/hooks/use-create-output-mutation";
import type { CreateOutputPayload, OutputRecord, ProjectSummary } from "@/lib/types";

const outputSchema = z.object({
  projectId: z.string().min(1, "请选择项目"),
  date: z.string().min(1, "请选择日期"),
  value: z
    .string()
    .min(1, "请输入产值")
    .refine((val) => Number(val) > 0, "产值必须大于 0"),
  note: z.string().max(500, "备注最多 500 字").optional(),
});

export type OutputFormValues = z.infer<typeof outputSchema>;

interface OutputFormProps {
  projects: ProjectSummary[];
  onSubmitted?: (output: OutputRecord) => void;
}

export function OutputForm({ projects, onSubmitted }: OutputFormProps) {
  const mutation = useCreateOutputMutation();
  const hasProjects = projects.length > 0;
  const today = useMemo(() => new Date().toISOString().slice(0, 10), []);

  const defaultProjectId = projects[0]?.id ?? "";

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<OutputFormValues>({
    resolver: zodResolver(outputSchema),
    defaultValues: {
      projectId: defaultProjectId,
      date: today,
      value: "",
      note: "",
    },
  });

  const onSubmit = handleSubmit(async (values) => {
    if (!hasProjects) {
      toast.error("当前暂无可用项目，请先创建项目后再提交");
      return;
    }

    const payload: CreateOutputPayload = {
      projectId: values.projectId,
      date: values.date,
      value: Number(values.value),
      note: values.note?.trim() ? values.note.trim() : undefined,
    };

    try {
      const created = await mutation.mutateAsync(payload);
      toast.success("产值上报成功", {
        description: `${created.projectName} · ${new Date(created.date).toLocaleDateString()} · ${created.value.toLocaleString()}`,
      });

      reset({
        projectId: values.projectId,
        date: values.date,
        value: "",
        note: "",
      });

      onSubmitted?.(created);
    } catch (error) {
      const message = error instanceof Error ? error.message : "提交失败，请稍后再试";
      toast.error(message);
    }
  });

  if (!hasProjects) {
    return (
      <div className="rounded-lg border border-dashed border-border bg-muted/40 p-6 text-sm text-muted-foreground">
        暂无可用项目。请先在排产页创建或导入项目，再进行日报上报。
      </div>
    );
  }

  return (
    <form className="space-y-5" onSubmit={onSubmit} noValidate>
      <div className="grid gap-4 sm:grid-cols-2">
        <div className="space-y-2">
          <label className="text-sm font-medium text-foreground" htmlFor="projectId">
            项目
          </label>
          <select
            id="projectId"
            className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
            disabled={mutation.isPending}
            {...register("projectId")}
          >
            <option value="" disabled>
              请选择项目
            </option>
            {projects.map((project) => (
              <option key={project.id} value={project.id}>
                {project.name}
              </option>
            ))}
          </select>
          {errors.projectId ? (
            <p className="text-xs text-destructive">{errors.projectId.message}</p>
          ) : null}
        </div>

        <div className="space-y-2">
          <label className="text-sm font-medium text-foreground" htmlFor="date">
            上报日期
          </label>
          <input
            id="date"
            type="date"
            className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
            max={today}
            disabled={mutation.isPending}
            {...register("date")}
          />
          {errors.date ? <p className="text-xs text-destructive">{errors.date.message}</p> : null}
        </div>
      </div>

      <div className="space-y-2">
        <label className="text-sm font-medium text-foreground" htmlFor="value">
          产值（元）
        </label>
        <input
          id="value"
          type="number"
          step="0.01"
          min="0"
          className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
          placeholder="请输入本次完成的产值"
          disabled={mutation.isPending}
          {...register("value")}
        />
        {errors.value ? <p className="text-xs text-destructive">{errors.value.message}</p> : null}
      </div>

      <div className="space-y-2">
        <label className="text-sm font-medium text-foreground" htmlFor="note">
          备注（可选）
        </label>
        <textarea
          id="note"
          rows={4}
          className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm shadow-sm transition focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary"
          placeholder="如需说明进度、问题或无产值原因，可在此填写"
          disabled={mutation.isPending}
          {...register("note")}
        />
        {errors.note ? <p className="text-xs text-destructive">{errors.note.message}</p> : null}
      </div>

      <div className="flex items-center justify-end gap-3">
        <button
          type="submit"
          disabled={mutation.isPending}
          className="inline-flex items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition hover:bg-primary/90 disabled:cursor-not-allowed disabled:opacity-65"
        >
          {mutation.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : null}
          {mutation.isPending ? "提交中" : "提交上报"}
        </button>
      </div>
    </form>
  );
}
